import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:olii/common/services/AiService.dart';

class AiController extends GetxController {
  AiController();

  final ImagePicker _picker = ImagePicker();
  final AIService _aiService = AIService();

  Rx<File?> selected_image = Rx<File?>(null);
  RxBool is_loading = false.obs;
  RxBool is_picking_image = false.obs;
  RxString result_text = ''.obs;
  RxString plant_name = ''.obs;
  RxDouble confidence_score = 0.0.obs;
  RxString plant_care_info = ''.obs;
  RxBool is_loading_care_info = false.obs;

  // 添加结构化数据的变量
  RxString care_information = ''.obs;
  RxString flowering_time = ''.obs;
  RxString common_problems = ''.obs;

  // 添加识别进度状态
  RxString recognition_stage = ''.obs;
  RxDouble recognition_progress = 0.0.obs;

  _initData() {
    debugPrint('初始化数据...');
    _aiService.init();
    update(["ai"]);
  }

  // 从相册选择图片
  Future<void> pick_image() async {
    debugPrint('从相册选择图片...');
    is_picking_image.value = true;
    update(["ai"]);

    try {
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        selected_image.value = File(image.path);
        debugPrint('已选择图片，路径: ${image.path}');
      } else {
        debugPrint('用户取消了图片选择');
      }
    } finally {
      is_picking_image.value = false;
      update(["ai"]);
    }
  }

  // 使用相机拍照
  Future<void> take_photo() async {
    debugPrint('启动相机拍照...');
    final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
    if (photo != null) {
      selected_image.value = File(photo.path);
      debugPrint('已拍摄照片，路径: ${photo.path}');
      update(["ai"]);
    } else {
      debugPrint('用户取消了拍照');
    }
  }

  // 使用AI服务识别植物
  Future<void> recognize_plant() async {
    if (selected_image.value == null) {
      debugPrint('错误：未选择图片');
      return;
    }

    debugPrint('开始识别植物...');
    is_loading.value = true;
    recognition_stage.value = 'Starting recognition';
    recognition_progress.value = 0.0;
    result_text.value = '';
    plant_name.value = '';
    confidence_score.value = 0.0;
    plant_care_info.value = '';
    // 清空结构化数据
    care_information.value = '';
    flowering_time.value = '';
    common_problems.value = '';
    update(["ai"]);

    try {
      // 图像处理阶段
      recognition_stage.value = 'Processing image...';
      recognition_progress.value = 0.3;
      update(["ai"]);

      await Future.delayed(Duration(milliseconds: 200));

      // 植物识别阶段
      recognition_stage.value = 'Identifying plant species...';
      recognition_progress.value = 0.5;
      update(["ai"]);

      final result = await _aiService.recognize_plant(selected_image.value!);

      // 获取养护信息阶段
      recognition_stage.value = 'Retrieving care information...';
      recognition_progress.value = 0.8;
      update(["ai"]);

      if (result['success']) {
        plant_name.value = result['plantName'];
        confidence_score.value = result['score'];
        plant_care_info.value = result['careInfo'];

        // 处理结构化数据
        if (result.containsKey('careDetails')) {
          final details = result['careDetails'] as Map<String, dynamic>;
          care_information.value = _improve_formatting(details['careInfo'] ?? '');
          flowering_time.value = _improve_formatting(
            details['floweringTime'] ?? '',
          );
          common_problems.value = _improve_formatting(
            details['commonProblems'] ?? '',
          );

          debugPrint('提取到结构化养护信息：');
          debugPrint('养护信息: ${care_information.value}');
          debugPrint('开花时间: ${flowering_time.value}');
          debugPrint('常见问题: ${common_problems.value}');
        }

        result_text.value = 'Plant identified successfully';
        debugPrint('成功识别植物: ${plant_name.value}');
      } else {
        result_text.value = result['error'];
        debugPrint('识别失败: ${result['error']}');
      }

      // 处理完成
      recognition_stage.value = 'Completed';
      recognition_progress.value = 1.0;
      update(["ai"]);
    } catch (e) {
      debugPrint('识别植物时发生错误: $e');
      result_text.value = 'Error: $e';
      recognition_stage.value = 'Recognition failed';
    } finally {
      is_loading.value = false;
      debugPrint('植物识别流程结束');
      update(["ai"]);
    }
  }

  // 额外处理格式化文本，确保列表显示正确
  String _improve_formatting(String text) {
    if (text.isEmpty) return '';

    // 处理空白行和多余的空格
    String formatted = text.trim().replaceAll(RegExp(r'\s{2,}'), ' ');

    // Keep formatting simple - just ensure bullet points are formatted correctly
    formatted = formatted.replaceAll("-", "•");
    formatted = formatted.replaceAll(" • ", "\n• ");
    formatted = formatted.replaceAll("•", "• ");

    // Remove any special formatting that might interfere with clean display
    formatted = formatted.replaceAll("*", "");
    formatted = formatted.replaceAll("**", "");
    formatted = formatted.replaceAll("#", "");

    // Fix any double spaces
    formatted = formatted.replaceAll("  ", " ");

    // Replace any escape characters
    formatted = formatted.replaceAll('\$1\\n\\n\$2', '');
    formatted = formatted.replaceAll('\$1\\n\$2', '');
    formatted = formatted.replaceAll('\$3', '');
    formatted = formatted.replaceAll('\\\\n', '\n');

    return formatted;
  }

  // 清除当前结果
  void clear_result() {
    debugPrint('清除当前结果...');
    selected_image.value = null;
    result_text.value = '';
    plant_name.value = '';
    confidence_score.value = 0.0;
    plant_care_info.value = '';
    // 清空结构化数据
    care_information.value = '';
    flowering_time.value = '';
    common_problems.value = '';
    recognition_stage.value = '';
    recognition_progress.value = 0.0;
    update(["ai"]);
    debugPrint('已清除所有结果数据');
  }

  // 提问植物相关问题
  Future<void> ask_follow_up_question(String question) async {
    debugPrint('发送后续问题: $question');
    is_loading_care_info.value = true;
    update(["ai"]);

    try {
      final answer = await _aiService.ask_follow_up_question(question);
      // 添加markdown格式的问答
      plant_care_info.value += '\n\n**问题：**\n\n$question\n\n**回答：**\n\n$answer';
      debugPrint('收到回答');
    } catch (e) {
      debugPrint('提问时发生错误: $e');
    } finally {
      is_loading_care_info.value = false;
      update(["ai"]);
    }
  }

  @override
  void onReady() {
    super.onReady();
    debugPrint('AiController 准备就绪');
    _initData();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
